package com.complaint.rest.security;

import com.complaint.rest.security.dto.Role;
import com.complaint.rest.rc.RestClient;
import com.complaint.rest.security.dto.ExampleUserDetails;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * Created by Alex
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        com.complaint.rest.model.User user = RestClient.get().getUserByEmail(s);
        if (user == null) {
            throw new UsernameNotFoundException("Username not found");
        }
        return buildUserFromUserEntity(user);
    }

    private ExampleUserDetails buildUserFromUserEntity(com.complaint.rest.model.User userEntity) {
        ExampleUserDetails userDetails = ExampleUserDetails.getBuilder()
                .firstName(userEntity.getFirstName())
                .id(userEntity.getId())
                .lastName(userEntity.getLastName())
                .password(userEntity.getPassword())
                .role(Role.ROLE_USER)
                .username(userEntity.getEmail())
                .build();
        return userDetails;
    }
}
